// @/utils/shareUtils.js
import { ImgBaseUrl } from "@/utils/domain.js";

export class ShareManager {
  /**
   * 初始化分享配置
   * @param {Object} options - 分享配置选项
   * @param {Function} options.getShareInfo - 获取分享信息的函数
   * @param {Object} options.popupRef - 分享弹窗引用
   */
  constructor(options) {
    // 验证必要参数
    if (!options.getShareInfo) {
      throw new Error('getShareInfo function is required');
    }
    this.getShareInfo = options.getShareInfo;
    this.popupRef = options.popupRef;
  }

  /**
   * 打开分享弹窗
   */
  openSharePopup() {
    if (this.popupRef && this.popupRef.value) {
      console.log('Opening popup via ShareManager');
      this.popupRef.value.open();
    } else {
      console.error('Popup reference is not available');
    }
  }

  /**
   * 关闭分享弹窗
   */
  closeSharePopup() {
    if (this.popupRef && this.popupRef.value) {
      this.popupRef.value.close();
    }
  }

  /**
   * 配置全局分享
   * @returns {Object} 分享配置
   */
  configShareAppMessage() {
    const shareInfo = this.getShareInfo();
    return {
      path: shareInfo.path || '',
      title: shareInfo.title || '推荐一位优质服务者',
      imageUrl: shareInfo.imageUrl || `${ImgBaseUrl}banner.png`
    };
  }

  /**
   * 执行分享操作
   * @param {String} type - 分享类型(weixin, qq等)
   */
  async doShare(type) {
    try {
      const shareInfo = this.getShareInfo();
      
      // 显示分享菜单
      await uni.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage']
      });

      // 根据类型执行不同平台的分享
      if (type === 'weixin') {
        // 检查是否在微信环境
        const platform = uni.getSystemInfoSync().platform;
        if (platform !== 'ios' && platform !== 'android') {
          throw new Error('请在微信客户端中使用分享功能');
        }
        
        const result = await uni.share({
          provider: 'weixin',
          scene: 'WXSceneSession',
          type: 0,
          title: shareInfo.title,
          imageUrl: shareInfo.imageUrl,
          path: shareInfo.path,
        });
        
        console.log('分享成功', result);
        this.closeSharePopup();
        return true;
      }
      
    } catch (err) {
      console.error('分享失败', err);
      uni.showToast({
        title: err.message || '分享失败',
        icon: 'none'
      });
      return false;
    }
  }
}